<?php

namespace app\ruinuo\controller\design;

use app\common\model\RuinuoSetting;
use think\facade\Request;
use app\common\model\RuinuoApp;
use app\common\model\RuinuoMode;
use app\common\model\RuinuoControl;
use app\common\model\RuinuoForm;
use app\ruinuo\design\FormLayout as CurdForm;
use app\common\controller\Component as thatComponent;
use app\common\middleware\Auth;
class Form
{
    protected $middleware = [Auth::class => []];
    /*加载控件*/
    public function Index()
    {
        if (Request::isAjax() || Request::isPost()) {
            $RuinuoControl = new RuinuoControl();
            $data['config'] = [];
            $allMode = GetOptions('mode_list');
            $options = [
                'verify' => GetOptions('verify_list'),
                'GridNum' => $this->GridNum(),
                'options_col' => $this->Col(),
                'options_list' => GetOptions('options_list'),
                'date_cat' => $this->DateTime(),
                'yesno' => GetOptions('yesno'),
                'upload_type' => GetOptions('upload_type'),
                'database_list' => GetOptions('database_list'),
                'allmode' => $allMode,
                'allmode_url' => $this->ModeUrl(),
                'code_field' => ['rows' => []]
            ];
            $design = $RuinuoControl->where("is_cat=1")->field("id,name")->orderRaw('sort asc,id desc')->select()->toArray();
            foreach ($design as $k => $v) {
                $children = $RuinuoControl->where("is_cat=2 and parent_id='" . $v['id'] . "'")->field("name,num,icon,config")->orderRaw('sort asc,id desc')->select()->toArray();
                foreach ($children as $kk => $vv) {
                    if ($vv['config']) {
                        $Form = $this->GetForm($vv['config']);

                        foreach ($Form as $kb => $vb) {
                            if ($vb['field'] == "title") {
                                $Form[$kb]['value'] = $vv['name'];
                            }
                            if ($vb['tag'] == "select") {
                                $Form[$kb]['data'] = [];
                                if ($vb['field'] == "date_cat") {
                                    $Form[$kb]['data'] = $options['date_cat'];
                                    $Form[$kb]['value'] = 'date';
                                }
                                if ($vb['field'] == "grid_num") {
                                    $Form[$kb]['data'] = $options['GridNum'];
                                }
                            }

                            if ($vb['field'] == "options_num") {
                                $Form[$kb]['value'] = 'yesno';
                            }

                            if ($vb['field'] == "verify") {
                                $Form[$kb]['data'] = $options['verify'];
                                if ($vv['num'] == "phone") {
                                    $Form[$kb]['value'] = 'isphone';
                                }
                                if ($vv['num'] == "email") {
                                    $Form[$kb]['value'] = 'isemail';
                                }
                                if ($vv['num'] == "number") {
                                    $Form[$kb]['value'] = 'isinteger';
                                }
                            }


                            if ($vv['num'] == "tab" && $vb['field'] == "children") {
                                $Form[$kb]['cols'] = [['title' => '名称', 'field' => 'name', 'update' => 'input']];
                                $Form[$kb]['value'] = [['name' => 'TAB1', 'children' => []], ['name' => 'TAB2', 'children' => []]];
                            }
                            if ($vv['num'] == "grid" && $vb['field'] == "children") {
                                $Form[$kb]['cols'] = [['title' => '栅格数', 'field' => 'num', 'update' => 'input']];
                                $Form[$kb]['value'] = [['num' => '6', 'children' => []], ['num' => '6', 'children' => []]];
                            }
                        }
                        $config = $this->AllForm($Form);
                        $data['config'][$vv['num']] = $config;
                    }
                }
                $design[$k]['children'] = $children;
            }
            $data['design'] = $design;
            $data['modelist'] = $this->ModeList(1);
            $data['source'] = $options;
            return BackCode($data);
        }
        return ViewTpl('ruinuo/design/form');
    }

    public function Form()
    {
        $params = input();
        $layout = !empty($params['layout']) ? json_decode($params['layout'], true) : [];
        $async=!empty($params['async']) ? $params['async'] : 1;
        $CurdForm = new CurdForm();
        $data['html'] = $CurdForm->GetForm($layout,$async);
        if (input('async') == 1) {
            $fields = $CurdForm->GetFormField($layout);
            $data['source'] = [];
            foreach ($fields as $k => $v) {
                if (!empty($v['options_num'])) {
                    $data['source'][$v['options_num']] = GetOptions($v['options_num']);
                }
            }
        }
        return BackCode($data);
    }

    /*查询模块*/
    public function ModeList($v_type = '')
    {
        $RuinuoApp = new RuinuoApp();
        $RuinuoMode = new RuinuoMode();
        $RuinuoSetting = new RuinuoSetting();
        $type = input("type") ?: 1;
        $arr = [];
        switch ($type) {
            case 1:
                $arr = $RuinuoApp->field("id,name")->select()->toArray();
                foreach ($arr as $k => $v) {
                    $children = $RuinuoMode->where("app_id='" . $v['id'] . "'")->field("id,name")->select()->toArray();
                    $arr[$k]['children'] = $children;
                    if (empty($children)) {
                        unset($arr[$k]);
                    }
                }
                break;
            case 2:
                $arr = $RuinuoSetting->field("id,group_num")->group("group_num")->select()->toArray();
                foreach ($arr as $k => $v) {
                    $arr[$k]['name'] = $v['group_num'];
                    $children = $RuinuoSetting->where("group_num='" . $v['group_num'] . "'")->field("id,name,group_num")->select()->toArray();
                    $arr[$k]['children'] = $children;
                }
                break;
        }
        $arr = array_values($arr);
        if ($v_type) {
            return $arr;
        }
        $data['modelist'] = $arr;
        return BackCode($data);
    }

    /*查询表单*/
    public function FormFind()
    {
        $RuinuoMode = new RuinuoMode();
        $RuinuoForm = new RuinuoForm();
        $id = input('id');
        $type = input('type') ?: 1;
        if (empty($id)) {
            return BackCode([], '204', '请传入参数');
        }
        $database = [];
        $data = [];
        switch ($type) {
            case 1:
                $mode = $RuinuoMode->where("id='" . $id . "'")->field('database,name,num,id,sub_database')->find();
                if (empty($mode)) {
                    return BackCode([], '204', '没有此模块');
                }
                $thatComponent = new thatComponent();
                $data = $RuinuoForm->where("mode_id='" . $id . "'")->field('layout,form_label,label_width,id')->find();
                if (empty($data)) {
                    $upData = [
                        'mode_id' => $id,
                    ];
                    $data['id'] = $RuinuoForm->insertGetId($upData);
                }

                $sub_database = !empty($mode['sub_database']) ? json_decode($mode['sub_database'], true) : [];
                $key = $thatComponent->DataBase($mode['database']);
                $database = $key['rows'];
                foreach ($sub_database as $k => $v) {
                    if ($v['type'] == 1) {
                        $item = $thatComponent->DataBase($v['database'], $v['alias']);
                        $database[] = $item['rows'][0];
                    }
                }
                break;
            case 2:
                $RuinuoSetting = new RuinuoSetting();
                $data = $RuinuoSetting->where("id='" . $id . "'")->field("id,layout,form_label,label_width,fields,name,num")->find();
                if (!empty($data)) {
                    $fields = !empty($data['fields']) ? json_decode($data['fields'], true) : [];
                    $children = [];
                    foreach ($fields as $k => $v) {
                        $children[] = [
                            'label' => $v['title'] . '_' . $v['field'],
                            'value' => $v['field'],
                        ];
                    }
                    $database = [[
                        'label' => $data['name'] . $data['num'],
                        'value' => $data['num'],
                        'children' => $children,
                    ]];
                    unset($data['fields']);
                    unset($data['name']);
                    unset($data['num']);
                }
                break;
        }
        $data['layout'] = !empty($data['layout']) ? json_decode($data['layout'], true) : [];
        $data['label'] = !empty($data['form_label']) ? $data['form_label'] : 'form_right';
        $data['label_width'] = !empty($data['label_width']) ? $data['label_width'] : '100';
        $data['database'] = ['rows' => $database];
        return BackCode($data);
    }

    /*修改或者新增表单*/
    public function UpLayout()
    {
        if (Request::isAjax() || Request::isPost()) {
            $id = input("id");
            $type = input("type") ?: 1;
            if (empty(input("id")) || empty(input("layout"))) {
                return BackCode([], '203', '请传入参数');
            }
            $updata = [
                'layout' => json_encode(json_decode(input("layout"), true), JSON_UNESCAPED_UNICODE),
            ];
            switch ($type) {
                case 1:
                    $RuinuoForm = new RuinuoForm();
                    $count = $RuinuoForm->where("mode_id='" . $id . "'")->count();
                    if (!empty($count)) {
                        $updata['update_time'] = date('Y-m-d H:i:s');
                        $updata['update_id'] = GetToken('id') ?: 0;
                        $RuinuoForm->where("`mode_id`='" . $id . "'")->Update($updata);
                    } else {
                        $updata['create_time'] = date('Y-m-d H:i:s');
                        $updata['create_id'] = GetToken('id') ?: 0;
                        $updata['mode_id'] = input('id');
                        $RuinuoForm->insert($updata);
                    }
                    break;
                case 2:
                    $RuinuoSetting = new RuinuoSetting();
                    $updata['update_time'] = date('Y-m-d H:i:s');
                    $updata['update_id'] = GetToken('id') ?: 0;
                    $RuinuoSetting->where("`id`='" . $id . "'")->Update($updata);
                    break;
            }
            return BackCode();
        }
    }

    /*获取基本配置*/
    public function GetForm($field)
    {
        $arr = explode(",", $field);
        $rows = [];
        $config = $this->FormConfig();
        foreach ($arr as $k => $v) {
            $rows[$k] = $config[$v];
            $rows[$k]['field'] = $v;
        }
        return $rows;
    }

    /*补齐参数*/
    public function AllForm($arr = [])
    {
        $config = $this->FormConfig();
        $RuinuoControl = new RuinuoControl();
        foreach ($arr as $k => $v) {
            $find = $RuinuoControl->where("num='" . $v['tag'] . "'")->field("config")->find();
            $list = explode(",", $find['config']);
            foreach ($list as $kk => $vv) {
                $value = !empty($config[$vv]['value']) ? $config[$vv]['value'] : '';
                if (!isset($v[$vv])) {
                    $arr[$k][$vv] = $value;
                }
            }
        }
        return $arr;
    }

    public function FormConfig()
    {
        $config = [
            'field' => ['title' => '选择字段', 'tag' => 'select', 'options_num' => 'database_field'],
            'title' => ['title' => '标题', 'tag' => 'input'],
            'prefix' => ['title' => '前缀', 'tag' => 'icon'],
            'suffix' => ['title' => '后缀', 'tag' => 'icon'],
            'placeholder' => ['title' => '占位提示', 'tag' => 'input'],
            'group_prefix' => ['title' => '文字前缀', 'tag' => 'input'],
            'group_suffix' => ['title' => '文字后缀', 'tag' => 'input'],
            'help' => ['title' => '帮助文档', 'tag' => 'textarea', 'height' => 60],
            'value' => ['title' => '默认值', 'tag' => 'input'],
            'col' => ['title' => '宽度', 'tag' => 'select', 'value' => '12', 'options_num' => 'options_col'],
            'verify' => ['title' => '验证', 'tag' => 'select', 'options_num' => 'verify'],
            'readonly' => ['title' => '是否禁用', 'tag' => 'switch', 'value' => 2],
            'range' => ['title' => '日期范围', 'tag' => 'switch', 'value' => 2],
            'range_field' => ['title' => '范围结束字段', 'tag' => 'select', 'options_num' => 'database_field'],
            'hide_label' => ['title' => '隐藏标题', 'tag' => 'switch', 'value' => 2],
            'hide' => ['title' => '是否隐藏', 'tag' => 'switch', 'value' => 2],
            'required' => ['title' => '是否必填', 'tag' => 'switch', 'value' => 2],
            'is_curd' => ['title' => '允许操作', 'tag' => 'switch', 'value' => 1],
            'only' => ['title' => '是否唯一值', 'tag' => 'switch', 'value' => 2],
            'follow' => ['title' => '是否跟进', 'tag' => 'switch', 'value' => 2],
            'is_all' => ['title' => '允许多选', 'tag' => 'switch', 'value' => 2],
            'is_shot' => ['title' => '允许拍摄', 'tag' => 'switch', 'value' => 2],
            'height' => ['title' => '高度', 'tag' => 'number', 'value' => 100],
            'text' => ['title' => '显示文字', 'tag' => 'input', 'value' => '是|否'],
            'show_cat' => ['title' => '显示方式', 'tag' => 'select'],
            'date_cat' => ['title' => '日期类型', 'tag' => 'select', 'options_num' => 'date_cat'],
            'file_type' => ['title' => '存储方式', 'tag' => 'select', 'options_num' => 'upload_type'],
            'file_select' => ['title' => '允许选择', 'tag' => 'switch', 'value' => 2],
            'file_num' => ['title' => '上传多个', 'tag' => 'switch', 'value' => 2],
            'min_val' => ['title' => '最小值', 'tag' => 'number', 'value' => 1],
            'max_val' => ['title' => '最大值', 'tag' => 'number', 'value' => 100],
            'options_num' => ['title' => '数据源', 'tag' => 'select', 'options_num' => 'options_list'],
            'content' => ['title' => '内容', 'tag' => 'textarea', 'value' => '示例内容'],
            'grid_num' => ['title' => '栅格数', 'tag' => 'select', 'value' => '2'],
            'children' => ['title' => '设置', 'tag' => 'jsontable', 'cols' => [], 'value' => []],
            'html_content' => ['title' => 'html内容', 'tag' => 'htmledit', 'height' => 400, 'value' => ''],
            'open_url' => ['title' => 'Url地址', 'tag' => 'input'],
            'choose_url' => ['title' => 'Url地址', 'tag' => 'input','placeholder'=>'填写之后可选择新增'],
            'cols' => ['title' => '表格配置', 'tag' => 'textarea', 'hide' => 1],
            'max_width' => ['title' => '最大宽度', 'tag' => 'number', 'value' => 180],
            'code_field' => ['title' => '关联字段', 'tag' => 'select', 'options_num' => 'code_field'],
            'gongshi_txt' => ['title' => '计算函数', 'tag' => 'input', 'hide' => 1],
            'event_val' => ['title' => '事件值', 'tag' => 'textarea', 'hide' => 1],
            'mode_url' => ['title' => '选择模型', 'tag' => 'select', 'options_num' => 'allmode_url'],
            'num_rule' => ['title' => '编号规则', 'tag' => 'textarea', 'readonly' => 1],
            'mode_id' => ['title' => '选择模型', 'tag' => 'select', 'options_num' => 'allmode'],
            'mode_sub_id' => ['title' => '模型关联ID', 'tag' => 'input', 'value' => ''],
            'mode_sub_post' => ['title' => '列表过滤参数', 'tag' => 'input', 'value' => ''],
            'database' => ['title' => '存储到子表', 'tag' => 'select', 'options_num' => 'database_list'],
            'database_field' => ['title' => '子表关联字段', 'tag' => 'input', 'value' => ''],
        ];
        return $config;
    }


    public function Browse()
    {
        if (Request::isAjax() || Request::isPost()) {

            $params = input();
            $layout = !empty($params['layout']) ? json_decode($params['layout'], true) : [];
            $CurdForm = new CurdForm();
            $data['html'] = $CurdForm->GetForm($layout);
            $fields = $CurdForm->GetFormField($layout);
            $data['detail'] = [];
            $data['source'] = [];
            foreach ($fields as $k => $v) {
                $data['detail'][$v['field']] = !empty($v['value']) ? $v['value'] : '';
                if (!empty($v['options_num'])) {
                    $data['source'][$v['options_num']] = GetOptions($v['options_num']);
                }
                $cols = !empty($v['cols']) ? $v['cols'] : [];
                foreach ($cols as $kk => $vv) {
                    if (!empty($vv['options'])) {
                        $data['source'][$vv['options']] = GetOptions($vv['options']);
                    }

                }


            }
            return BackCode($data);

        };
        return ViewTpl('ruinuo/design/browse');
    }


    public function GridNum()
    {
        $data['rows'] = [
            ['label' => 2, 'value' => 2],
            ['label' => 3, 'value' => 3],
            ['label' => 4, 'value' => 4],
            ['label' => 6, 'value' => 6],
            ['label' => 12, 'value' => 12],
        ];
        return $data;
    }

    public function Col()
    {
        $data['rows'] = [
            ['label' => '整行', 'value' => 12],
            ['label' => '1/4', 'value' => 3],
            ['label' => '1/3', 'value' => 4],
            ['label' => '1/2', 'value' => 6],
            ['label' => '2/3', 'value' => 8],
            ['label' => '3/4', 'value' => 9],
        ];
        return $data;
    }


    public function DateTime()
    {
        $data['rows'] = [
            ['label' => '年', 'value' => 'year'],
            ['label' => '年月', 'value' => 'month'],
            ['label' => '年月日', 'value' => 'date'],
            ['label' => '时分秒', 'value' => 'time'],
            ['label' => '年月日时分秒', 'value' => 'datetime'],
        ];
        return $data;
    }


    public function ModeUrl()
    {

        $RuinuoApp = new RuinuoApp();
        $RuinuoMode = new RuinuoMode();
        $arr = $RuinuoApp->field("id,name,num")->select()->toArray();
        foreach ($arr as $k => $v) {
            $arr[$k]['label'] = $v['name'] . "_" . $v['num'];
            $arr[$k]['value'] = $v['num'];
            $children = $RuinuoMode->where("app_id='" . $v['id'] . "'")->field("id,name,num")->select()->toArray();
            foreach ($children as $kk => $vv) {
                $children[$kk]['label'] = $vv['name'] . "_" . $vv['num'];
                $children[$kk]['value'] = "/" . $v['num'] . "/" . $vv['num'] . '/lists/';
            }
            $arr[$k]['children'] = $children;
            if (empty($children)) {
                unset($arr[$k]);
            }
        }
        $data['rows'] = array_values($arr);
        return $data;
    }


}